//
//  TempSaveExt.swift
//  ANOA
//
//  Created by 邱仙凯 on 2023/7/12.
//  Copyright © 2023 zwb. All rights reserved.
//

import UIKit


extension ConfigMenuForm {
    // 单个模板处理附件草稿事件
    func singleTempConfigFile(imgArray:[VideoImg],backJson:@escaping((String)->())) {
        KSNetwork.shared.doRequest(API.temp(.uploadFileByMenuId(menuId: self.rootTemp.id_key.unwrap,files: imgArray))) { (data:BaseResult<DraftFileResult>) in
            var ddc = ""
            if data.flag == TRUE {
                let infoD = data.infoDicArr
                
                ddc = dictionaryToJsonBack(infoD).unwrap
                
                
            }
            backJson(ddc)
        }
    }
    
    /// 三目运算符处理, 目前只写了主表字段的支持
    func doTernaryOperat(_ exp: String) -> String? {
        
        guard exp.contains("?") else { return nil }
        
        let subExp = exp.components(separatedBy: "?")
        
        guard subExp.count == 2 else {
            KSToast("联系管理员,编号979898")
            return nil
        }
        
        let express = subExp.first!
        
        var currValue: Int?
        var value: Int = 0
        var operateExp = subExp.first!
        let getValues = subExp.last!.components(separatedBy: ":")
        var operate = ""
        guard getValues.count == 2 else {
            KSToast("联系管理员,编号979898")
            return nil
        }
        
        if express.contains("a.") {
            operateExp = operateExp.replace(old: "a.", str: "").replace(old: "{", str: "").replace(old: "}", str: "")
        }
        
        if operateExp.contains(">") {
            operate = ">"
        } else if operateExp.contains("<") {
            operate = "<"
        } else if operateExp.contains("<=") {
            operate = "<="
        } else if operateExp.contains(">=") {
            operate = ">="
        } else if operateExp.contains("!=") {
            operate = "!="
        } else if operateExp.contains("==") || operateExp.contains("=") {
            operate = "="
        }
        
        if express.contains("a.") {
            guard let realKey = operateExp.preChar(char: operate) else {
                return nil
            }
            
            currValue = intTran(self.main[realKey].unwrap)
        }
        
        value = intTran(operateExp.sufChar(char: operate).unwrap)
        
        
        if currValue != nil {
            if operateExp.contains(">") {
                return currValue! > value ? getValues.first : getValues.last
            } else if operateExp.contains("<") {
                return currValue! < value ? getValues.first : getValues.last
            } else if operateExp.contains("<=") {
                return currValue! <= value ? getValues.first : getValues.last
            } else if operateExp.contains(">=") {
                return currValue! >= value ? getValues.first : getValues.last
            } else if operateExp.contains("!=") {
                return currValue != value ? getValues.first : getValues.last
            } else if operateExp == "==" || operateExp.contains("=") {
                return currValue == value ? getValues.first : getValues.last
            }
        } else {
            return getValues.last
        }
        
        return nil
    }
    
    // 语法: setFormButton@{a.c_status}=1?取消提交:提交修改
    /// 配置保存按钮的文字
    func configSaveTitle() {
        if self.rootTemp.setFormButtonTitle {
            let formButtonArr = self.rootTemp.grmmarArr.filter { $0.contains(GrammarType.setFormButton.rawValue) }
            for xxx in formButtonArr {
                
                var brrrr = getKeyPara(xxx)
                brrrr.remove(at: 0)
                
                for itemX in brrrr {
                    
                    var isKeepView = false
                    
                    
                    if itemX.rangeOf(str: "$").length > 0 {
                        let subItemx = itemX.components(separatedBy: "$")
                        if !isKeepView && subItemx.last == "悬浮" {
                            isKeepView = true
                        }
                        
                        submitButton.button.extTitle(title: doTernaryOperat(subItemx[0]))
                        
                    } else {
                        if submitButton.superview != nil {
                            submitButton.button.extTitle(title: doTernaryOperat(itemX))
                        }
                    }
                    
                    if isKeepView {
                        
                        tableVw.tableFooterView = FootRoundView()
                        
                        let footer = FootRoundView().extBgColor(color: .white)
                        for subView in footer.subviews {
                            if subView.ks_height == 8 {
                                subView.removeFromSuperview()
                            }
                        }
                        footer.addSubV(subv: footSubmit)
                        footer.ks_height += heightOfAddtionalFooter
                        footer.ks_y = KS_SCREEN_HEIGHT - (ksStatusbarHeight + ksNavigationbarHeight + footer.ks_height)
                        view.addSubview(footer)
                    }
                }
            }
            
            
        }
    }
    
    // 保存按钮  事件等 初始化一次性处理，期间不会变动
    func configSaveAc() -> FootRoundView {
        let footerv = FootRoundView()
        
        if self.excuteType == .add || self.excuteType == .fix {
            if self.excuteType == .add && rootTemp.setContinueAdd {
                footerv.addSubV(subv: footSubmitAndAdd)
                tableVw.tableFooterView = footerv
            } else {
                if TempAppear.shared.enableDraft && self.excuteType == .add {
                    footerv.addSubV(subv: footSubmitAndDraft)
                    tableVw.tableFooterView = footerv
                } else {
                    
                    footerv.addSubV(subv: footSubmit)
                    
                    tableVw.tableFooterView = footerv
                    
                }
                
            }
        } else if self.excuteType == .auditing || self.excuteType == .audited {
            
            
            let checkV =  newGetFlowView(auditParamCombine: self.tempAuditParamC, vc: self)
            
            footerv.addSubV(subv: checkV.0)
            tableVw.tableFooterView = footerv
            
            self.tableVw.reloadData()
            if   self.tempAuditParamC!.appr.jueseType != .viewer {
                self.view.addSubview(checkV.1)
                checkV.1.snp.makeConstraints { make in
                    make.left.right.bottom.equalToSuperview()
                    make.height.equalTo(70)
                }
            }
            
            
            
        } else {
            tableVw.tableFooterView = footerv
            
        }
        
        if self.rootTemp.is_save_and_refer == "1" {
            submitButton.button.setTitle("保存并提交", for: .normal)
        } else {
            submitButton.button.setTitle("保存", for: .normal)
        }
        // MARK: - 保存草稿
        submitDraftButton.button.addTouchUpInSideAction { _ in
            configMain { dd in
                var resultMain = dd
                
                if self.rootTemp.multiDetailsParams.count > 0 {
                    
                    var hasfile = false
                    for u in 0..<self.rootTemp.multiDetailsParams.count {
                        let oneColumn = self.detHandler[u]
                        let hA = oneColumn.filter{$0.imgArray.count > 0}
                        if hA.count > 0 {
                            hasfile = true
                        }
                    }
                    if hasfile {
                        // 创建调度组
                        let workingGroup = DispatchGroup()
                        for i in 0..<self.rootTemp.multiDetailsParams.count {
                            // 入组
                            workingGroup.enter()
                            configOneColumn(oneColumn: self.detHandler[i]) { bdic in
                                resultMain.updateValue(bdic, forKey: self.rootTemp.multiDetailsParams[i])
                                workingGroup.leave()
                            }
                        }
                        
                        // 调度组里的任务都执行完毕
                        workingGroup.notify(queue: .main) {
                            finalSaveDraft(resultMain: resultMain)
                        }
                        
                    } else {
                        
                        for i in 0..<self.rootTemp.multiDetailsParams.count {
                            var deJson = self.detHandler[i].compactMap { dictionaryToJson($0.dic) }.joined(separator: ",")
                            deJson = "[\(deJson)]"
                            resultMain.updateValue(deJson, forKey: self.rootTemp.multiDetailsParams[i])
                        }
                        finalSaveDraft(resultMain: resultMain)
                        
                    }
                    
                    
                    
                } else {
                    
                    
                    configOneColumn(oneColumn: self.detHandler[0]) { bdic in
                        resultMain.updateValue(bdic, forKey: TKey.details)
                        finalSaveDraft(resultMain: resultMain)
                    }
                    
                }
                
                
                
            }
            func finalSaveDraft(resultMain:[String:Any]) {
                let dic = dictionaryToJson(resultMain)
                
                KSNetwork.shared.doRequest(API.temp(.saveDraft(userId: USERINFO.idKey.unwrap, menuId: self.rootTemp.id_key.unwrap, data: dic))) { (data:BaseResult<OperateResult>) in
                    if data.flag == TRUE {
                        KSToast("保存成功")
                        self.backAction()
                    } else {
                        KSToast(data.errorCombine.unwrap)
                    }
                    
                }
            }
            // 处理一组细表
            func configOneColumn(oneColumn:[DetailsTempCom],backDic:@escaping((String)->())) {
                
                var oneColumnDic = oneColumn.compactMap { $0.dic }
                
                let hasFileArr = oneColumn.filter{ $0.imgArray.count > 0 }
                if hasFileArr.count > 0 {
                    
                    // 创建调度组
                    let workingGroup = DispatchGroup()
                    
                    for i in 0..<oneColumn.count {
                        if oneColumn[i].imgArray.count > 0 {
                            
                            if let indx = oneColumn[i].temp.getIndexFor({ tone in
                                return tone.field_type == TemplateType.file.rawValue
                            })  {
                                // 入组
                                workingGroup.enter()
                                self.singleTempConfigFile(imgArray: oneColumn[i].imgArray) { ddc in
                                    oneColumnDic[i].updateValue(ddc, forKey: "\(oneColumn[i].temp[indx].field_nm.unwrap)#file_dic")
                                    workingGroup.leave()
                                }
                            }
                            
                        }
                    }
                    
                    // 调度组里的任务都执行完毕
                    workingGroup.notify(queue: .main) {
                        
                        backDic(dictionaryToJson_noprint(oneColumnDic).unwrap)
                        
                    }
                } else {
                    let cdic = dictionaryToJson_noprint(oneColumn.compactMap{ $0.dic })
                    backDic(cdic.unwrap)
                    
                }
                
                
            }
            func configMain(backDic:@escaping(([String:Any])->())) {
                var ddMain = self.main
                
                
                let hasFileArr = self.mainHandler.filter{ $0.temp?.field_type == TemplateType.file.rawValue && $0.imgArray.count > 0 }
                if hasFileArr.count > 0 {
                    
                    
                    
                    // 创建调度组
                    let workingGroup = DispatchGroup()
                    
                    
                    
                    for i in 0..<self.mainHandler.count {
                        let item = self.mainHandler[i]
                        
                        if item.temp!.field_type == TemplateType.file.rawValue,item.imgArray.count > 0 {//附件类型
                            
                            // 入组
                            workingGroup.enter()
                            self.singleTempConfigFile(imgArray: item.imgArray) { ddc in
                                ddMain.updateValue(ddc, forKey: "\(item.temp!.field_nm.unwrap)#file_dic")
                                workingGroup.leave()
                            }
                            
                            
                        }
                    }
                    
                    // 调度组里的任务都执行完毕
                    workingGroup.notify(queue: .main) {
                        
                        backDic(ddMain)
                        
                    }
                } else {
                    backDic(ddMain)
                }
                
                
            }
            
            
        }
        
        submitButton.button.addTouchUpInSideAction { _ in
            self.beginSaveAc()
        }
        submitAndAddBtn.button.addTouchUpInSideAction { _ in
            self.valiAction { flag in
                if flag {
                    self.tempSaveAction {
                        
                        self.uploadimgAction {
                            self.continueRefer()
                        } upFail: { dealarr,error in
                            alertUtil(title: "单据保存成功，附件保存失败,\(error.localizedDescription)，确认继续",withCancel: false, operateS: [nameAction(name: "确认", action: { _ in
                                self.continueRefer()
                            })])
                        }
                        
                    }
                }
            }
        }
        
        return footerv
    }
    // 渔美康过来，有可能传1 ，1会突破一些限制，可以特殊保存单据
    func beginSaveAc(is_root:String = "0") {
        self.valiAction { flag in
            if flag {
                self.tempSaveAction(is_root:is_root) {
                    
                    self.uploadimgAction {
                        if self.rootTemp.is_save_and_refer == "1" {
                            self.referAction {
                                self.backAction()
                            }
                        } else {
                            self.backAction()
                        }
                    } upFail: { dealarr,error in
                        alertUtil(title: "单据保存成功，附件保存失败,\(error.localizedDescription),确认继续",withCancel: false, operateS: [nameAction(name: "确认", action: { _ in
                            
                            
                            if self.rootTemp.is_save_and_refer == "1" {
                                self.referAction {
                                    self.backAction()
                                }
                            } else {
                                self.backAction()
                            }
                        })])
                    }
                    
                    
                    
                    
                }
            }
        }
    }
    // MARK: - 读取草稿
    func configRight() {
        
        let rightbtn = UIButton.creat4Item(title: "读取草稿",color: .black) { _ in
            if !self.readingDraft {
                self.readingDraft = true
                self.readedDraft = true
                self.addJoinBaseData(dicCome: self.draftDic,fromDraft: true)
            }
            
        }
        
        self.draftBtn = UIBarButtonItem(customView:rightbtn)
        
        if self.excuteType == .add {
            KSNetwork.shared.doRequest(API.temp(.queryDraft(userId: USERINFO.idKey.unwrap, menuId: self.rootTemp.id_key.unwrap))) { (data:BaseResult<OperateResult>) in
                if data.flag == TRUE {
                    if let infoddd = data.infoDic {
                        self.draftDic = infoddd
                        
                        
                        
                        
                    }
                    
                    self.navigationItem.rightBarButtonItem = self.draftBtn
                    
                    
                } else {
                    
                }
            }
        }
        
    }
    
    
    
    // 继续提交操作
    func continueRefer() {
        if self.rootTemp.is_save_and_refer == "1" {
            self.referAction {
                self.dealSaveAndAdd()
            }
        } else {
            self.dealSaveAndAdd()
        }
    }
    // 处理保存并新增保留的数据
    func dealSaveAndAdd() {
        var tempADic = [String:Any]()
        for a in self.rootTemp.continueParamsA {
            tempADic[a] = self.main[a]
        }
        self.main = deepMerge(self.beginMain, tempADic)
        
        
        if self.rootTemp.continueParamsB.count > 0 {
            var tempBDicArr = Array(repeating: [[String:Any]](), count: 4)
            
            
            
            
            
            for mm in 0..<self.detHandler.count {
                
                let aDetArr = self.detHandler[mm]
                var ddddd = [[String:Any]]()
                for xx in aDetArr {
                    let aDic = xx.dic
                    var tempBDic = [String:Any]()
                    for a in self.rootTemp.continueParamsB {
                        tempBDic[a] = aDic[a]
                    }
                    ddddd.append(tempBDic)
                }
                tempBDicArr[mm] = ddddd
            }
            
            
            
            self.detHandler.removeAll()
            
            for mm in 0..<tempBDicArr.count {
                
                let aaaD = tempBDicArr[mm]
                
                for i in 0..<aaaD.count {
                    let aDic = aaaD[i]
                    var onell = self.beginDetHandler[i]
                    onell.dic = deepMerge(onell.dic, aDic)
                    self.detHandler[i].append(onell)
                    
                }
            }
            
            
            
        } else {
            for i in 0..<self.beginDetHandler.count {
                self.detHandler[i] = [self.beginDetHandler[i]]
            }
            
            
        }
        
        
        self.configTempDataSource()
        if let clo = self.refreshClosure {
            clo()
        }
    }
    /// 单个字段 依赖校验
    func dependenceVali(onexx:TemplateModel,indexPath:IndexPath?) -> Bool {
        
        
        let hasReg = onexx.grmmarArr.filter{ $0.contains(GrammarType.setDependenceField.rawValue) }
        guard  hasReg.count > 0 else {
            return true
        }
        
        let vali = Validation()
        // 依赖校验
        for xxx in hasReg {
            let arrrr = getKeyPara(xxx)
            guard arrrr.count > 0 else {
                KSToast("联系管理员,编号979898")
                return false
            }
            if arrrr.first! == GrammarType.setDependenceField.rawValue {
                
                var brrrr = arrrr
                brrrr.remove(at: 0)
                
                for itemX in brrrr {
                    let sepA = itemX.components(separatedBy: ":")
                    guard sepA.count == 2 else {
                        KSToast("联系管理员,编号979898")
                        return false
                    }
                    
                    let condition = sepA[0]
                    
                    if condition.contains("b.") {
                        let realKey = condition.replacingOccurrences(of: "b.", with: "")
                        if indexPath.isSome {
                            let msg = "第\(indexPath!.section + 1)条细表，\(sepA[1])"
                            vali.required(value: self.detHandler[self.cDIndex][indexPath!.section].dic[realKey], msg: msg)
                        } else {
                            KSToast("确认主细表和a.b.")
                        }
                    } else if condition.contains("a.")  {
                        let realKey = condition.replacingOccurrences(of: "a.", with: "")
                        let msg = "\(sepA[1])"
                        vali.required(value: self.main[realKey], msg: msg)
                        
                    } else if condition.contains(".") {
                        
                        
                        
                        //定义的细表回填
                        let dPaNm = condition.preChar(char: ".").unwrap
                        let realKey = condition.sufChar(char: ".").unwrap
                        
                        if let dIndex = self.rootTemp.multiDetailsParams.getIndexFor({ one in
                            one == dPaNm
                        }) {
                            
                            let msg = "\(self.rootTemp.multiDetailsTitles[dIndex]),第\(indexPath!.section + 1)条细表,\(sepA[1])"
                            vali.required(value: self.detHandler[dIndex][indexPath!.section].dic[realKey], msg: msg)
                            
                        } else {
                            KSToast("联系管理员，88599")
                            
                        }
                        
                        
                    } else {
                        if indexPath.isSome {
                            let msg = "\(self.rootTemp.multiDetailsTitles[self.cDIndex]),第\(indexPath!.section + 1)条细表,\(sepA[1])"
                            vali.required(value: self.detHandler[self.cDIndex][indexPath!.section].dic[condition], msg: msg)
                        } else {
                            
                            let msg = "\(sepA[1])"
                            vali.required(value: self.main[condition], msg: msg)
                        }
                        
                    }
                    
                    
                    
                    
                }
                guard vali.validate() else {
                    return false
                }
            }
        }
        return true
    }
    
    
    
    func valiAction(resultClo:@escaping((Bool)->())) {
        
        // 个人档案特殊处理, "取消提交"跳过验证
        if self.rootTemp.setFormButtonTitle {
            if let title = submitButton.button.titleLabel?.text, title.contains("取消") {
                resultClo(true)
                return
            }
        }
        
        // 表单的判空在多分区的时候不顶用了需要手动判断
        //        guard self.judgeNoNone() else {
        //            return
        //        }
        
        // 不能提取为方法，因为涉及到阻止，提取方法需要单独写阻止
        let vali_f = Validation()
        
        // 主表表单的判空
        for i in 0..<self.mainHandler.count {
            let onexx = self.mainHandler[i].temp!
            // 显示且必填 需要校验
            if onexx.is_required == "1" &&
                isShowJ(onexx,auCombine: self.tempAuditParamC,exType: self.excuteType) &&
                onexx.field_type != TemplateType.file.rawValue {
                vali_f.required(value:self.main[onexx.field_nm.unwrap], msg: "\(onexx.field_annotation.unwrap)不为空！")
            }
        }
        
        // 附件的下限个数校验
        let imgAr = self.mainHandler.filter{ $0.temp!.field_type == TemplateType.file.rawValue }
        for xo in imgAr {
            if xo.temp?.is_required == "1" {
                vali_f.expression(xo.imgArray.count >= 1, msg: "\(xo.temp!.field_annotation.unwrap),附件必填")
            } else {
                let min = intTran(xo.temp!.upload_num_min)
                if min > 0 {
                    vali_f.expression(xo.imgArray.count >= min, msg: "\(xo.temp!.field_annotation.unwrap),附件最少需要\(min)个")
                }
            }
        }
        
        
        guard vali_f.validate() else {
            return
        }
        // 不能提取为方法，因为涉及到阻止，提取方法需要单独写阻止
        let valiDetails = Validation()
        
        // 细表判空校验
        var detailSectionCount = 1
        if rootTemp.multiDetailsParams.count > 0 {
            detailSectionCount = rootTemp.multiDetailsParams.count
        }
        
        for u in 0..<detailSectionCount {
            for i in 0..<self.detHandler[u].count {
                let temp = self.detHandler[u][i].temp
                for y in 0..<temp.count {
                    let onexx = temp[y]
                    // 显示且必填 需要校验
                    if onexx.is_required == "1" &&
                        isShowJ(onexx, auCombine: self.tempAuditParamC, exType: self.excuteType)
                        && onexx.field_type != TemplateType.file.rawValue {
                        var sectionName = ""
                        if u < self.rootTemp.multiDetailsTitles.count {
                            sectionName = self.rootTemp.multiDetailsTitles[u]
                            valiDetails.required(value:self.detHandler[u][i].dic[onexx.field_nm.unwrap], msg: "\(sectionName),第\(i + 1)条，\(onexx.field_annotation.unwrap)不为空！")
                        } else {
                            valiDetails.required(value:self.detHandler[u][i].dic[onexx.field_nm.unwrap], msg: "第\( u + 1)组,第\(i + 1)条，\(onexx.field_annotation.unwrap)不为空！")
                        }
                    }
                    
                    if onexx.field_type == TemplateType.file.rawValue {
                        
                        if onexx.is_required == "1" {
                            vali_f.expression(self.detHandler[u][i].imgArray.count >= 1, msg: "\(onexx.field_annotation.unwrap),附件必填")
                            if self.detHandler[u][i].imgArray.count < 1 {
                                KSToast("\(onexx.field_annotation.unwrap),附件必填")
                                resultClo(false)
                                return
                            }
                        } else {
                            let min = intTran(onexx.upload_num_min)
                            if min > 0 {
                                vali_f.expression(self.detHandler[u][i].imgArray.count >= min, msg: "\(onexx.field_annotation.unwrap),附件最少需要\(min)个")
                            }
                        }
                    }
                    
                }
            }
        }
        
        
        
        
        // 采用全提示
        guard valiDetails.validateCollect() else {
            return
        }
        
        
        let valiX = Validation()
        
        // 主表正则逻辑校验
        let regVArr = self.mainHandler.filter { onexx in
            let hasReg = onexx.temp!.grmmarArr.filter{ $0.contains(GrammarType.setRegularExp.rawValue) }
            return hasReg.count > 0
        }
        
        // 主表赋值附件个数
        for xo in 0..<self.mainHandler.count {
            let theone = self.mainHandler[xo]
            if theone.temp!.field_type == TemplateType.file.rawValue {
                let paNm = theone.temp!.field_nm.unwrap
                let imCount = theone.imgArray.count
                self.main[paNm] = "\(imCount)"
                KSLog("-主表-\(paNm)--附件--\(imCount)个")
            }
        }
        
        
        
        
        
        
        
        
        
        
        // 细表赋值附件个数
        
        for u in 0..<detailSectionCount {
            for i in 0..<self.detHandler[u].count {
                let dic = self.detHandler[u][i].dic
                // 给细表附件数量赋值，用于保存校验
                let fileParamArr = self.detHandler[u][i].temp.filter{$0.field_type == TemplateType.file.rawValue}
                if fileParamArr.count > 0 {
                    let paNm = fileParamArr.first!.field_nm.unwrap
                    let imCount = self.detHandler[u][i].imgArray.count
                    self.detHandler[u][i].dic[paNm] = "\(imCount)"
                    KSLog("-第\(i + 1)条-\(paNm)--附件--\(imCount)个")
                }
            }
        }
        
        
        
        
        
        
        
        
        
        // 正则逻辑校验
        for oneGrA in regVArr {
            for xxx in oneGrA.temp!.grmmarArr {
                let arrrr = getKeyPara(xxx)
                guard arrrr.count > 0 else {
                    return
                }
                if arrrr.first! == GrammarType.setRegularExp.rawValue {
                    var brrrr = arrrr
                    brrrr.remove(at: 0)
                    
                    for itemX in brrrr {
                        var resultArr = [String]() // 3段
                        var tempS = ""
                        itemX.forEach { c in
                            let s = String(c)
                            if s == ":" && resultArr.count < 3 {
                                resultArr.append(tempS)
                                tempS = ""
                            }  else {
                                tempS += s
                            }
                        }
                        resultArr.append(tempS)
                        let regExp = resultArr[2]
                        
                        // {b.z_num}<=0
                        let str = any2Str(self.main[oneGrA.temp!.field_nm.unwrap])
                        let boolFlag = RegularExpression(regex: regExp, validateString: str)
                        if resultArr[0] == "1" {
                            valiX.expression(boolFlag, msg: "\(resultArr[1])")
                        } else {
                            valiX.expression(boolFlag, msg: "\(resultArr[1])",stop: false)
                        }
                    }
                }
            }
        }
        
        
        
        // 细表正则逻辑校验
        for i in 0..<self.detHandler[self.cDIndex].count {
            let dic = self.detHandler[self.cDIndex][i].dic
            
            let regVArr = self.detHandler[self.cDIndex][i].temp.filter { onexx in
                let hasReg = onexx.grmmarArr.filter{ $0.contains(GrammarType.setRegularExp.rawValue) }
                return hasReg.count > 0
            }
            
            // 正则逻辑校验
            for oneGrA in regVArr {
                for xxx in oneGrA.grmmarArr {
                    let arrrr = getKeyPara(xxx)
                    guard arrrr.count > 0 else {
                        return
                    }
                    if arrrr.first! == GrammarType.setRegularExp.rawValue {
                        var brrrr = arrrr
                        brrrr.remove(at: 0)
                        
                        for itemX in brrrr {
                            var resultArr = [String]() // 3段
                            var tempS = ""
                            itemX.forEach { c in
                                let s = String(c)
                                if s == ":" && resultArr.count < 3 {
                                    resultArr.append(tempS)
                                    tempS = ""
                                }  else {
                                    tempS += s
                                }
                            }
                            resultArr.append(tempS)
                            let regExp = resultArr[2]
                            
                            // {b.z_num}<=0
                            let str = any2Str(dic[oneGrA.field_nm.unwrap])
                            let boolFlag = RegularExpression(regex: regExp, validateString: str)
                            if resultArr[0] == "1" {
                                valiX.expression(boolFlag, msg: "第\(i+1)条细表，\(resultArr[1])")
                            } else {
                                valiX.expression(boolFlag, msg: "第\(i+1)条细表，\(resultArr[1])",stop: false)
                            }
                        }
                    }
                }
            }
        }
        
        
        
        
        // 表达式逻辑校验
        let saveVArr = rootTemp.grmmarArr.filter{ $0.contains(GrammarType.setSaveVerify.rawValue) }
        
        // 表达式逻辑校验
        for xxx in saveVArr {
            let arrrr = getKeyPara(xxx)
            guard arrrr.count > 0 else {
                return
            }
            if arrrr.first! == GrammarType.setSaveVerify.rawValue {
                
                var brrrr = arrrr
                brrrr.remove(at: 0)
                
                
                
                for itemX in brrrr {
                    let sepA = itemX.components(separatedBy: ":")
                    guard sepA.count == 3 else {
                        KSToast("setSaveVerify语法，联系管理员")
                        return
                    }
                    
                    let condition = sepA[0]
                    // 包含了细表元素
                    if containDDPa(condition: condition, rootTemp: rootTemp)  != ""  {  // 细表表达式处理    里面也可以取值带a.的
                        
                        if rootTemp.multiDetailsParams.count > 0 {
                            for yy in 0..<rootTemp.multiDetailsParams.count {
                                let itemx = rootTemp.multiDetailsParams[yy]
                                if condition.contains("\(itemx).") {
                                    for i in 0..<self.detHandler[yy].count {
                                        let dedic = self.detHandler[yy][i].dic
                                        
                                        let boolFlag =  expressionReplace(condition,main:self.main, currDet: dedic,rootTemp: rootTemp)
                                        let msg = "第\(yy+1)组\(i+1)条细表，\(sepA[2])"
                                        if sepA[1] == "1" {
                                            valiX.expression(boolFlag, msg: msg)
                                        } else {
                                            valiX.expression(boolFlag, msg: msg,stop: false)
                                        }
                                    }
                                }
                                
                            }
                        } else {
                            
                            
                            for i in 0..<self.detHandler[0].count {
                                let dedic = self.detHandler[0][i].dic
                                
                                let boolFlag =  expressionReplace(condition,main:self.main, currDet: dedic,rootTemp: rootTemp)
                                let msg = "第\(i+1)条细表，\(sepA[2])"
                                if sepA[1] == "1" {
                                    valiX.expression(boolFlag, msg: msg)
                                } else {
                                    valiX.expression(boolFlag, msg: msg,stop: false)
                                }
                            }
                            
                        }
                        
                        
                        
                    } else {
                        let boolFlag =  expressionReplace(condition,main:self.main, currDet: nil,rootTemp: rootTemp)
                        if sepA[1] == "1" {
                            valiX.expression(boolFlag, msg: sepA[2])
                        } else {
                            valiX.expression(boolFlag, msg: sepA[2],stop: false)
                        }
                    }
                    
                    
                }
                
                
                
            }
            
        }
        
        
        // 细表唯一性校验
        let detUniqueVArr = rootTemp.grmmarArr.filter{ $0.contains(GrammarType.setDetailUnique.rawValue) }
        
        // 细表唯一性校验
        for xxx in detUniqueVArr {
            let arrrr = getKeyPara(xxx)
            guard arrrr.count > 0 else {
                return
            }
            if arrrr.first! == GrammarType.setDetailUnique.rawValue {
                
                var brrrr = arrrr
                brrrr.remove(at: 0)
                
                for itemX in brrrr {
                    let sepA = itemX.components(separatedBy: ":")
                    guard sepA.count == 3 else {
                        KSToast("三段式示例：setDetailUnique@{b.z_one_no:0:细表个体号不能重复}")
                        return
                    }
                    
                    let condition = sepA[0]
                    
                    // 细表表达式处理
                    let detPa = containDDPa(condition: condition, rootTemp: rootTemp)
                    if detPa != "" {
                        var tempAA = [String]()
                        var fflag = true
                        
                        var iddd = 0
                        if let muindex = rootTemp.multiDetailsParams.getIndexFor({ onexx in
                            onexx == detPa
                        }) {
                            iddd = muindex
                        }
                        
                        
                        for i in 0..<self.detHandler[iddd].count {
                            let dedic = self.detHandler[iddd][i].dic
                            let reKey = condition.replacingOccurrences(of: "\(detPa).", with: "")
                            let reValue = any2Str(dedic[reKey])
                            if tempAA.contains(reValue) {
                                fflag = false
                                break
                            } else {
                                tempAA.append(reValue)
                            }
                        }
                        
                        let msg = "\(sepA[2])"
                        if sepA[1] == "1" {
                            valiX.expression(fflag, msg: msg)
                        } else {
                            valiX.expression(fflag, msg: msg,stop: false)
                        }
                        
                    } else {
                        KSToast("\(condition)\n语法有误")
                    }
                    
                }
                
                
                
            }
            
        }
        
        
        
        guard valiX.validate() else {
            return
        }
        
        valiX.validatexAsyncColle { flag in
            resultClo(flag)
        }
    }
    
    
    
    @objc func tempSaveAction(is_root:String = "0",saveSuccess:@escaping(()->())) {
        
        guard saveingProtect == "" else {
            
            SKPSMTPMeService.shared.startUploadLog(contact:"press save when netting\n耗时操作:\(saveingProtect)\n\(saveingProjectInfo)\n", remark: Date.nowTimeToSecond, imgs: [] )
            KSToast("正在\(saveingProtect)中，请等待")
            return
        }
        saveingProtect = "保存单据"
        saveingProjectInfo = "菜单模板: \(self.title.unwrap)\n"
        TempLog("菜单模板-\(self.title.unwrap)--执行保存")
       
        var masterjson = dictionaryToJson(self.main)
        
      
        if TempAppear.shared.decodeJson {
            masterjson = masterjson.removeLineFeed
        }
        
        var dic = [String:String]()
        dic.updateValue(masterjson, forKey: rootTemp.MainParam)
        if self.rootTemp.multiDetailsParams.count > 0 {
            
            for i in 0..<self.rootTemp.multiDetailsParams.count {
                var deJson = self.detHandler[i].compactMap { dictionaryToJson($0.dic) }.joined(separator: ",")
                deJson = "[\(deJson)]"
                dic.updateValue(deJson, forKey: self.rootTemp.multiDetailsParams[i])
            }
        } else {
            var deJson = self.detHandler[self.cDIndex].compactMap { dictionaryToJson($0.dic) }.joined(separator: ",")
            deJson = "[\(deJson)]"
            
            if TempAppear.shared.decodeJson {
                deJson = deJson.removeLineFeed
            }
            
            
            
            dic.updateValue(deJson, forKey: rootTemp.detParam)
         
        }
        if is_root == "1" {
            dic.updateValue("1", forKey: "is_root")
        }
  
        KSNetwork.shared.doRequest(API.temp(.path(path: rootTemp.path, paramDic: dic))) { (data:BaseResult<OperateResult>) in
            
            self.saveingProtect = ""
            
            if data.flag == TRUE {
                var successStr = "保存成功"
                if data.errorCombine.unwrap != "" {
                    successStr = data.errorCombine.unwrap
                }
                var dur:Int = 1
                let needDur = successStr.count / 15
                dur = needDur > dur ? needDur : dur
                KSLog("\(successStr.count)---时间--\(dur)")
                KSToast(successStr,duration: TimeInterval(dur))
                
              
                 if any2Str(self.main[TKey.id_key]) == "" {
                    TempLog("save返回了id_key,\(data.infoObjCombine?.idkey)")
//                    self.main[TKey.id_key] = data.infoObjCombine?.idkey
                     if let infodic = data.infoDic {
                         self.main = infodic
                     }
                     
                }
                if let det = data.infoDic?[TKey.details] as? [[String:Any]] {
                    
                    if det.count == self.detHandler[self.cDIndex].count {
                        for i in 0..<det.count {
                            self.detHandler[self.cDIndex][i].dic[TKey.id_key] = det[i][TKey.id_key]
                            TempLog("save返回了id_key，细表\(i+1):\(det[i][TKey.id_key])")
                            
                        }
                    }
                } else if let infoDic = data.infoDic {
                    
                    for (idx, key) in self.rootTemp.multiDetailsTitleKeys.enumerated() {
                        guard let arr = infoDic[key] as? [[String: Any]] else {
                            continue
                        }
                        
                        for i in 0..<arr.count {
                            if idx < self.detHandler.count {
                                self.detHandler[idx][i].dic[TKey.id_key] = arr[i][TKey.id_key]
                                TempLog("save返回了id_key，细表\(i+1):\(arr[i][TKey.id_key] ?? "")")
                            }
                        }
                    }
                }
                if self.readedDraft {
                    KSNetwork.shared.doRequest(API.temp(.deleteDraft(userId: USERINFO.idKey.unwrap, menuId: self.rootTemp.id_key.unwrap))) { (data:BaseResult<OperateResult>) in
                         
                            }
                }
               
                
                saveSuccess()
                
            } else {
                KSToast(data.errorCombine.unwrap)
            }
        }
        
        
    }
    
    
    func uploadimgAction(upImgsuccess:@escaping(()->()),upFail:@escaping(([VideoImg],KSNetworkError)->())) {
        saveingProtect = "保存附件"
        saveingProjectInfo = "菜单模板: \(self.title.unwrap)"
        TempLog("上传图片前，vouid == \(any2Str(self.main[TKey.id_key]))")
        // 创建调度组
        let workingGroup = DispatchGroup()
        // 主表附件上传
        let imgAA = self.mainHandler.filter{$0.imgArray.count > 0}
        for iii in imgAA {
            let unA = iii.imgArray.filter { $0.idkey == "" || $0.idkey == nil }
            // 没有idkey的为新添加的图片
            if unA.count > 0 {
                // 入组
                workingGroup.enter()
                dealVideoData(arr: unA) { dealArr in
                    tempUploadFileFun(templateDic: self.templateDic, module_id: self.rootTemp.module_id.unwrap, module_nm: self.rootTemp.menu_nm.unwrap, imgArray: dealArr, vouId: any2Str(self.main[TKey.id_key]),item: iii.temp, success: {
                        
                        // 出组
                        workingGroup.leave()
                    }) { (error) in
                        upFail(dealArr,error)
                        self.saveingProtect = ""
                    }
                }
            }
        }
        
        
        // 细表图片上传
        for (idx, subDetHandler) in self.detHandler.enumerated() {
            
            
            let ddImgAA = subDetHandler.filter { $0.imgArray.count > 0 }
            for iii in ddImgAA {
                let unA = iii.imgArray.filter { $0.idkey == "" || $0.idkey == nil }
                let oneDic = iii.dic
                
                TempLog("上传图片前，细表id == \(any2Str(oneDic[TKey.id_key]))")
                
                let temps = iii.temp
                let tempOne = temps.filter { $0.field_type == TemplateType.file.rawValue  }.first!
                if unA.count > 0 {
                    // 入组
                    workingGroup.enter()
                    dealVideoData(arr: unA) { dealArr in
                        tempUploadFileFun(templateDic: self.templateDic, module_id: self.rootTemp.module_id.unwrap, module_nm: self.rootTemp.menu_nm.unwrap, imgArray: dealArr, vouId: any2Str(oneDic[TKey.id_key]), item: tempOne, success: {
                            
                            // 出组
                            workingGroup.leave()
                        }) { (error) in
                            upFail(dealArr,error)
                            self.saveingProtect = ""
                        }
                    }
                }
            }
        }
        
        // 调度组里的任务都执行完毕
        workingGroup.notify(queue: .main) {
            self.saveingProtect = ""
            upImgsuccess()
        }
        
    }
    func referAction(reSuccess:@escaping(()->())) {
        
        let pathArrs = url2PathOriParam(self.rootTemp.refer_url.unwrap)
        let pathDic = url2PathDic(mainDic: self.main,arr: pathArrs.comPa)
        var diccc = pathDic
        diccc.updateValue(self.rootTemp.is_auditFlow.unwrap, forKey: "is_audit")
        diccc.updateValue(self.rootTemp.flow_voucd.unwrap, forKey: "flow_voucd")
        diccc.updateValue(self.rootTemp.flow_flownm.unwrap, forKey: "flow_flownm")
        TempLog("菜单模板-\(self.title.unwrap)--执行提交")
        saveingProtect = "提交单据"
        saveingProjectInfo = "菜单模板: \(self.title.unwrap)"
        KSNetwork.shared.doRequest(API.temp(.path(path: pathArrs.path, paramDic: diccc))) { (data:BaseResult<OperateResult>) in
            self.saveingProtect = ""
            if data.flag == TRUE {
                KSToast("提交成功")
                reSuccess()
            } else {
                KSToast(data.errorCombine.unwrap)
            }
        }
    }
    func backAction() {
        if let clo = self.refreshClosure {
            clo()
        }
        if self.backto.isNone {
            self.navigationController?.popViewController(animated: true)
        } else {
            
        
                for i in 0..<(self.navigationController?.viewControllers.count)! {
                    KSLog(self.navigationController?.viewControllers[i])
                    if self.navigationController?.viewControllers[i].isKind(of: self.backto!.self) == true {
                        _ = self.navigationController?.popToViewController(self.navigationController!.viewControllers[i], animated: true)
                        break
                    }
                }
                
         
            
        }
        
    }
    
}

